use crate::{db::connect_to_db, user::UserPost};
use anyhow::{Context, Result};
use futures::stream::StreamExt;
use mongodb::bson::doc;
use uuid::Uuid;
pub async fn count_unread_posts(user_id: Uuid) -> Result<u64> {
    let db = connect_to_db().await?;
    let _coll = db.collection::<UserPost>("userposts");
    let match1_aggr = doc! {
        "$match": {
        "user_id": user_id,
        "read": false,
        }
    };
    /*  let proj_aggr = doc! {
        "$project" :{
        "posts": 1
        }
    };
    let unset_aggr = doc! {
        "$unset": "_id"
    };
    let unwind_aggr = doc! {
        "$unwind": "$posts"
    };
    let match2_aggr = doc! {
        "$match":{
        "posts.read": false,
        }
    };*/
    let count_aggr = doc! {
        "$count" : "unreadPosts"
    };
    let pipeline = [
        match1_aggr,
        /*proj_aggr,
        unset_aggr,
        unwind_aggr,
        match2_aggr,
        */
        count_aggr,
    ];
    let options = None;
    let doc_count = _coll.aggregate(pipeline, options).await?.next().await;
    println!("{:#?}", doc_count);
    let doc_count = doc_count
        .context("count unread posts NoneError")?
        .context("test")?
        .get_i32("unreadPosts")
        .context("test2")? as u64;
    println!("{:#?}", doc_count);
    Ok(doc_count)
}
